package it.unipd.dei.es1011.nucularc0d3.defaultproject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class NewSession extends Activity implements OnSeekBarChangeListener{
	private TextView actualSeekBarValue;
	private TextView maxSensorValue;
	private TextView maxSeekBarValue;
	private SeekBar myBar;
	private CheckBox xAxis;
	private CheckBox yAxis;
	private CheckBox zAxis;
	private Spinner mySpinner;
	private Button myStartButton;
	private int samplingRate;
	private Context myContext = this;
	private SensorManager mySensorManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.new_session);

		Resources res = getResources(); // retrieve the value from the XML file /values/arrays.xml
		actualSeekBarValue = (TextView) findViewById(R.id.actualSeekBarTextView);
		maxSeekBarValue = (TextView) findViewById(R.id.maxSeekBarTextView);
		maxSeekBarValue.setText((res.getInteger(R.integer.seekBarMax)+1)+"");
		// retrieve Sensor Range, displaying it to the user
		mySensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
		maxSensorValue = (TextView) findViewById(R.id.maxSensorValue);
		maxSensorValue.setText("Notice! Maximum sensor range: "+mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER).getMaximumRange()
				+" G factor");
		// getting reference from XML
		myBar = (SeekBar) findViewById(R.id.seekBarTime);
		xAxis = (CheckBox) findViewById(R.id.checkboxPrefX);
		yAxis = (CheckBox) findViewById(R.id.checkboxPrefY);
		zAxis = (CheckBox) findViewById(R.id.checkboxPrefZ);
		mySpinner = (Spinner) findViewById(R.id.samplingRateSpinner);
		myStartButton = (Button) findViewById(R.id.startButton);
		// adding listener
		myBar.setOnSeekBarChangeListener(this);
		myStartButton.setOnClickListener(startRecording);
		// retrieving array of Sample rate from XML
		String[] arraySampleValue = res.getStringArray(R.array.samplingRateValues);
		int[] arraySampleValueInt = new int[arraySampleValue.length];
		for(int i=0;i<arraySampleValue.length;i++){
			arraySampleValueInt[i] = new Integer(arraySampleValue[i]);
		}
		samplingRate = arraySampleValueInt[1]; // default value loaded (in case of problem)

		//	load instance state
		if (savedInstanceState != null) {
			xAxis.setChecked(savedInstanceState.getBoolean("checkboxPrefX", true));
			yAxis.setChecked(savedInstanceState.getBoolean("checkboxPrefY", false));
			zAxis.setChecked(savedInstanceState.getBoolean("checkboxPrefZ", false));
			myBar.setProgress(savedInstanceState.getInt("seekBarTime", 0));
			samplingRate = savedInstanceState.getInt("samplingSpinner", samplingRate);
		} // if not,load preferences
		else{
			SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
			xAxis.setChecked(preferences.getBoolean("checkboxPrefX", true));
			yAxis.setChecked(preferences.getBoolean("checkboxPrefY", false));
			zAxis.setChecked(preferences.getBoolean("checkboxPrefZ", false));
			myBar.setProgress(preferences.getInt("seekBarTime", 0));

			try {
				samplingRate = new Integer(preferences.getString("samplingRate", samplingRate+""));
			} catch (NumberFormatException e) {
				// already set default value for sampling rate (before if)
			}
		}
		// select the right value of the spinner
		for(int i=0;i<arraySampleValueInt.length;i++)
			if(samplingRate == arraySampleValueInt[i])
				mySpinner.setSelection(i);

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		//		save the istance of Axis checked
		outState.putBoolean("checkboxPrefX", xAxis.isChecked());
		outState.putBoolean("checkboxPrefY", yAxis.isChecked());
		outState.putBoolean("checkboxPrefZ", zAxis.isChecked());
		//		save my seekBar value
		outState.putInt("seekBarTime", myBar.getProgress());
		//		save my spinner value
		outState.putInt("samplingSpinner", samplingRate);
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		// when the user change the progress this will set the new progress and update the text.
		seekBar.setProgress(progress);
		actualSeekBarValue.setText((progress+1)+"");
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// no need to implement
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// no need to implement
	}

	/**
	 * Here i define my button's listener. It will start the Recording activity passing
	 * the chosen preference.
	 */
	OnClickListener startRecording = new OnClickListener() {
		public void onClick(View v) {
			// create my intent, passing it the info for the recording
			if(xAxis.isChecked() || yAxis.isChecked() || zAxis.isChecked()){
				Intent i = new Intent(myContext, Recording.class);
				boolean[] axis = {xAxis.isChecked(),yAxis.isChecked(),zAxis.isChecked()};
				i.putExtra("axis", axis);
				i.putExtra("seekBarTime", myBar.getProgress());
				i.putExtra("spinnerSelected", mySpinner.getSelectedItemPosition());
				i.putExtra("samplingRate", samplingRate);
				startActivity(i);  
			}
			else // can't start a recording without axes to record :)
				Toast.makeText(getApplicationContext(), 
					    "An axis must be selected!!", 
					    Toast.LENGTH_LONG).show();
		}
	};

}
